﻿var _loadingLayers = {};
var _map;
var infoo;

function initMainLayer(onComplete){
	var cadastreLayer = new esri.layers.ArcGISDynamicMapServiceLayer(LAYERS_URL.cadastre);
	cadastreLayer.setImageFormat("png32");
	//cadastreLayer.hide();
	
	dojo.connect(cadastreLayer, "onLoad", function(){
		if (onComplete) 
			onComplete(cadastreLayer);
	});
}

function translateScalebar(){
	if(esri.dijit.Scalebar){
		esri.dijit.Scalebar.prototype._drawScaleBarOld = esri.dijit.Scalebar.prototype._drawScaleBar;
		esri.dijit.Scalebar.prototype._drawScaleBar = function(a,b,c){
			var c1 = ((c == 'km') ? ('км') : ('м'));
			this._drawScaleBarOld(a, b, c1);
		}
	}
}


function initMapAndLayers(mainLayer){
            var untiled;
            var tiled;
            var pureCoverage = false;
            // pink tile avoidance
            OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
            // make OL compute scale according to WMS spec
            OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
        
	    OpenLayers.ProxyHost = "http://212.26.144.107:8092/cgi-bin/proxy.cgi?url=";

	  
	    //var _map, infoo;
	    var mapBounds = new OpenLayers.Bounds( 21.921242623, 43.5341787107, 42.0119321532, 53.3790101853);
	    var mapMinZoom = 2;
	    var mapMaxZoom = 22

		        // avoid pink tiles
		        OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
		        OpenLayers.Util.onImageLoadErrorColor = "transparent";

		   var options = {
	                controls: [],
	                projection: new OpenLayers.Projection("EPSG:900913"),
	                displayProjection: new OpenLayers.Projection("EPSG:4326"),
	                units: "m",
			numZoomLevels: 22,
			maxResolution: 156543.0339,
	                maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
		            };
	        
		_map = new OpenLayers.Map('map', options); 


            
                // if this is just a coverage or a group of them, disable a few items,
                // and default to jpeg format
                format = 'image/png';
                if(pureCoverage) {
                    format = "image/png";
                }

/*  
                parcel = new OpenLayers.Layer.WMS(
                    "Ділянки", "http://212.26.144.107:8092/vector/geoserver/dzk/wms",
                    {
                        LAYERS: 'dzk:dilanka',
                        STYLES: '',
                        format: format,
			transparent: 'true',
                        tiled: true
                        //tilesOrigin : _map.maxExtent.left + ',' + _map.maxExtent.bottom
                    },
                    {
                        buffer: 0,
			//singleTile: true,
                        displayOutsideMaxExtent: true,
                        isBaseLayer: false,
                        yx : {'EPSG:900913' : false}
                    } 
                );
*/
		kadpodil = new OpenLayers.Layer.WMS(
                    "Кадастровий поділ", "http://212.26.144.107:8092/vector/geoserver/gwc/service/wms?tiled=true",
                    {
                        LAYERS: 'kadastr',
                        STYLES: '',
                        format: 'image/png',
                        tiled: true,
			transparent: 'true'
                        //tilesOrigin : _map.maxExtent.left + ',' + _map.maxExtent.bottom
                    },
                    {
                        buffer: 0,
			//singleTile: true,
                        displayOutsideMaxExtent: true,
                        isBaseLayer: false,
                        yx : {'EPSG:900913' : false}
                    } 
                );

		var gsat = new OpenLayers.Layer.Google(
    			"Google космос",
    			{type: google.maps.MapTypeId.SATELLITE, isBaseLayer: true, numZoomLevels: 22}
    			// used to be {type: G_SATELLITE_MAP, numZoomLevels: 22}
		); 


		var gphy = new OpenLayers.Layer.Google(
    			"Google карта",
    			{type: google.maps.MapTypeId.TERRAIN}
    			// used to be {type: G_PHYSICAL_MAP}
		);

		var gmap = new OpenLayers.Layer.Google(
    			"Google карта", // the default
    			{numZoomLevels: 22, isBaseLayer: true}
    			// default type, no change needed here
		);

		var ghyb = new OpenLayers.Layer.Google(
    			"Google Hybrid",
    			{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22}
    			// used to be {type: G_HYBRID_MAP, numZoomLevels: 20}
		);


	        // tmsoverlay = new OpenLayers.Layer.TMS( "100000", "",
	        //        {   // url: '', serviceVersion: '.', layername: '.',

		//				type: 'jpg', getURL: overlay_getTileURL, alpha: true, 
		//				isBaseLayer: true
	        //        });
		//		if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }




                _map.addLayers([kadpodil, gmap, gsat, ghyb]);

//cacheWrite = new OpenLayers.Control.CacheWrie({
//	autoActivate: true,
//	imageFormat: "image/png8"
//	});

                // build up all controls
                //_map.addControl(new OpenLayers.Control.PanZoomBar({position: new OpenLayers.Pixel(2, 15)}));
		_map.addControl(new OpenLayers.Control.Zoom());
                _map.addControl(new OpenLayers.Control.Navigation({dragPanOptions: {enableKinetic: true}}));
                _map.addControl(new OpenLayers.Control.Scale($('scale')));
                _map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
		_map.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')}));                

               _map.zoomToExtent( mapBounds.transform(_map.displayProjection, _map.projection ) );
//		_map.addControl(cacheWrite);

infoo = new OpenLayers.Control.WMSGetFeatureInfo({
            layersurl: 'http://212.26.144.107:8092/vector/geoserver/dzk/wms',
	    //layers: 'kadastr', 
            //url: 'http://212.26.144.1077:8092/vector/geoserver/gwc/service/wms',
	    title: 'Identify features by clicking',
            queryVisible: true,
            eventListeners: {
                getfeatureinfo: function(event) {
                    _map.addPopup(new OpenLayers.Popup.FramedCloud(
                        "chicken", 
                        _map.getLonLatFromPixel(event.xy),
                        null,
                        event.text,
                        null,
                        true
                    ));
                }
            }
        });
        _map.addControl(infoo);
        infoo.activate();
}

function setExtentByUrl(url,forPrint) {
    //url = location.search.substring(1);
    if (url.length > 0)
        url = url.substring(1);

    var parametr = url.split("&");

    var values = new Array();
    for (i in parametr) {
        var j = parametr[i].split("=");
        values[j[0]] = unescape(j[1]);
    }

    if (values["x"] != null && values["y"] != null) {
        var center = new esri.geometry.Point(parseFloat(values["x"]), parseFloat(values["y"]), new esri.SpatialReference({ "wkid": 102113 }));

        if (values["l"] != null)
            _map.centerAndZoom(center, parseInt(values["l"]));
        else
            _map.centerAt(center);

    } else {
      //  _map.setExtent(new esri.geometry.Extent(3000000, 5000000, 15000000, 11000000, new esri.SpatialReference({ "wkid": 102113 })));
    }

    if (values["mls"] != null) {
        var layersArray = values["mls"].split('|');
        for (i in _mapLayers) {
            if (contains(layersArray, i))
                _mapLayers[i].show();
            else
                _mapLayers[i].hide();
        }
    }
    if (values["cls"] != null) {
        var layersArray = values["cls"].split('|');
        for (i in _cadastreLayers) {
            if (contains(layersArray, i))
                _cadastreLayers[i].show();
            else
                _cadastreLayers[i].hide();
        }
    }
	if(!forPrint && values["ot"] && values["oid"]){
		searchObject(parseInt(values["ot"]), FIELDS.objectId+"="+values["oid"], forPrint);
	}
	if(!forPrint && values["cn"]){
		var t = getCadastreObjectType(values["cn"]);
		var cn = normalizeSearchCadastreNumber(normalizeCadastreNumber(values["cn"]));
		
		searchObject(t, getIdField(t) + " like '" + cn + "%'", forPrint);
	}
}

function contains(items, item) {
    for (var i = 0; i < items.length; i++) {
        if (items[i] == item) {
            return true;
        }
    }
    return false;
}

